﻿using System;
using System.Collections.Generic;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using YArchitech.Revit;

namespace YArchitech.Public
{
	[Transaction(TransactionMode.Manual)]
	[Regeneration(RegenerationOption.Manual)]
	public class HYAutoDrawing : HYExternalCommand
	{
		public override void FilterProcess()
		{
            base.FilterViewType.Remove((Autodesk.Revit.DB.ViewType)2);
            base.FilterViewType.Remove((Autodesk.Revit.DB.ViewType)1);
			base.FilterProcess();
		}

		public override Result HYExecute(ref string TranName)
		{
			TranName = "自动成图";
			List<Element> elementByCategory = YJKElementFilter.GetElementByCategory(base.Doc, BuiltInCategory.OST_Views);
			List<Element> list = new List<Element>();
			foreach (Element element in elementByCategory)
			{
				View view = (View)element;
                if (view.IsViewValidForSheet())
                {
					Parameter parameter = view.GetParameter(BuiltInParameter.VIEWPORT_SHEET_NUMBER);
					if ((parameter == null || !(parameter.AsString() != "") || parameter.AsString() == null) && this.HasElementByView(base.Doc, view))
					{
						list.Add(view);
					}
				}
			}
			List<Element> elementByCategory2 = YJKElementFilter.GetElementByCategory(base.Doc, BuiltInCategory.OST_Sheets);
			List<Element> elementByCategory3 = YJKElementFilter.GetElementByCategory(base.Doc, typeof(FamilySymbol), BuiltInCategory.OST_TitleBlocks);
			new ViewDrawingForm(list, elementByCategory2, elementByCategory3, base.Doc, "0")
			{
				Text = "布图管理"
			}.ShowDialog();
			return 0;
		}

		private bool HasElementByView(Document doc, View view)
		{
			IList<Element> list = new FilteredElementCollector(doc, view.Id).ToElements();
			if (list.Count == 0)
			{
				return false;
			}
			foreach (Element element in list)
			{
				if ((element.Category != null || !(element.Name == "ExtentElem")) && (element.Category == null || element.Category.Id.IntegerValue != -2000500))
				{
					return true;
				}
			}
			return false;
		}
	}
}
